/* -------------------- 通用工具函数库 --------------------- */

import appConfig from "../config/index";
import { ElMessage } from "element-plus";

/**
 * 获取鼠标选中的文本
 */
export function getSelections() {
  let userSelection = null;
  let text = "";
  // 一般浏览器
  if (window.getSelection) {
    const userSelectionStr = window.getSelection().toString();
    text = trim(userSelectionStr);
  }
  // IE浏览器、Opera
  else if (document.selection) {
    userSelection = document.selection.createRange();
    if (userSelection !== null) {
      const userSelectionStr = userSelection.text;
      text = trim(userSelectionStr);
    }
  }
  console.log("获取鼠标选中的文本 ==>", text);
  return text;
}

/**
 * 替换文本前与后的空格
 * @returns String
 */
export function trim(str) {
  if (typeof str !== "string") {
    return "";
  }
  return str.replace(/(^\s*)|(\s*$)/g, "");
}

/**
 * 使某个元素聚焦
 * @param {String} focusName 聚焦的元素id
 * @param {Boolean} isShow 下拉框菜单出现/隐藏时触发需回传的值
 */
export function focusElement(isShow = false, focusName = "searchBtn") {
  if (!isShow) {
    if (document.getElementById(focusName))
      document.getElementById(focusName).focus();
  }
}

/**
 * isInt = true 返回一个 开始数（包含） 和 结束数（包含） 中间的随机数（整数）
 *
 * isInt = false 返回一个 开始数（包含） 和 结束数（不包含） 中间的随机数（小数）
 * @param {*} min 开始数
 * @param {*} max 结束数
 * @returns
 */
export function getRandom(min, max, isInt = false) {
  if (isInt) {
    return Math.floor(Math.random() * (max - min + 1) + min);
  }
  return Math.random() * (max - min) + min;
}

/**
 * 处理图片相对路径，返回带 http 的可访问路径
 *
 * @param {*} imgUrl
 */
export function dealImgUrl(imgUrl) {
  let url = "";
  if (!imgUrl) {
    return url;
  }
  if (imgUrl.indexOf("http") === -1) {
    url = appConfig.fileDownloadUrl + "/" + imgUrl;
  } else {
    url = imgUrl;
  }
  return url;
}

/**
 * 将图片的绝对路径转换为base64编码
 *
 * @param {*} imgUrl
 * @returns
 */
export function getBase64Image(imgUrl) {
  return new Promise((resolve, reject) => {
    const image = new Image();
    // 解决图片跨域 - 注意顺序
    image.crossOrigin = "Anonymous";
    image.src = imgUrl;
    image.onload = function () {
      const canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(image, 0, 0, image.width, image.height);
      const ext = image.src
        .substring(image.src.lastIndexOf(".") + 1)
        .toLowerCase();
      const base64 = canvas.toDataURL("image/" + ext);
      console.log("base64 ==>", base64);
      resolve(base64);
    };
    image.onerror = function (err) {
      reject(err);
    };
  });
}

/**
 * base64的数据转换成blob
 *
 * @param {*} base64Str 例如： "......"
 */
export function base64TransferToBolb(base64Str) {
  const arr = base64Str.split(",");
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  const obj = new Blob([u8arr], { type: mime });
  return obj;
}

/**
 * ArrayBuffer 转 base64
 *
 * @param {*} buffer
 * @returns
 */
export const arrayBufferToBase64Img = (buffer) => {
  const str = String.fromCharCode(...new Uint8Array(buffer));
  return `data:image/jpeg;base64,${window.btoa(str)}`;
};

/**
 * 检测类型
 *
 * @param {*} data
 * @returns 返回类型字符串： string number boolean undefined null object function array date regExp object
 */
export const testType = (data) => {
  let type = Object.prototype.toString.call(data);
  type = type.slice(8, type.length - 1);
  return type.toLowerCase();
};

/**
 * 检测是否是空数组，空对象，空字符串
 *
 * @param {*} value
 * @returns true false
 */
export const isEmpty = (value) => {
  let isEmptyVal = false;
  const type = testType(value);
  switch (type) {
    case "array":
      if (value.length === 0) isEmptyVal = true;
      break;
    case "object":
      if (JSON.stringify(value) === "{}") isEmptyVal = true;
      break;
    case "string":
      if (value === "") isEmptyVal = true;
      break;
    case "undefined":
      isEmptyVal = true;
      break;
    case "null":
      isEmptyVal = true;
      break;
  }
  return isEmptyVal;
};

/**
 * 复制文本到剪切板
 *
 * @param {*} content
 * @returns
 */
export const copyInClip = (content) => {
  if (!document.queryCommandSupported("copy")) {
    ElMessage.warning("浏览器不支持此功能！");
    return;
  }
  const textarea = document.createElement("textarea");
  textarea.value = content;
  textarea.readOnly = "readOnly";
  document.body.appendChild(textarea);
  textarea.select();
  textarea.setSelectionRange(0, content.length);
  const result = document.execCommand("copy");
  if (result) {
    ElMessage.success("已复制到剪切板！");
  } else {
    ElMessage.error("复制失败！");
  }
  textarea.remove();
};

/**
 * 是否是移动端
 */
export function isPhone() {
  return /(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent);
}
